package viz_ui;

import java.awt.Color;

import buttons.control.C_VerticalDoubleSlider;

import processing.core.PApplet;

// Each line is comprised of a series of positions and a percent along an axis. 
// They are simple components but there are a lot of them in a single display.
public class ParallelLine {

	private float[][] positions; // an array of positions used for drawing this line
	private float[] yPercent; // an array of percentages used to determine if this line is filtered or not 
	private boolean selected;
	private boolean greyedOut;
	
	public ParallelLine(int length)
	{
		positions = new float[length][2];
		yPercent = new float[length];
	}
	
	public void addElement(int index, float xValue, float yValue, float percent)
	{
		positions[index][0] = xValue;
		positions[index][1] = yValue;
		yPercent[index] = percent;
	}
	
	public void swap(int leftIndex, int rightIndex, float leftPosition, float rightPosition)
	{
		float[] leftX = positions[leftIndex];
		float[] rightX = positions[rightIndex];
		positions[leftIndex] = new float[]{leftX[0], rightX[1]};
		positions[rightIndex] = new float[]{rightX[0], leftX[1]};
	}
	
	public void display(PApplet p)
	{
		// first determine stroke color for the line:
		p.stroke(0,0,0,200);
		if(selected)
		{
			p.strokeWeight(1.4f);
			p.stroke(Color.MAGENTA.getRGB());
		}
		else if(greyedOut)
		{
			p.stroke(50,50,50,5);
		}
		// then draw the line in a series of segments:
		for(int i = 0; i < positions.length; i++)
		{
			if(i < positions.length-1){
				p.line(positions[i][0], positions[i][1], positions[i+1][0], positions[i+1][1]);
			}
		}
		p.strokeWeight(1);
	}
	
	public void setSelected(boolean val)
	{
		selected = val;
	}
	
	public void setGrayedOut(boolean val)
	{
		greyedOut = val;
	}

	// Checks the range of all percentages recursively to determine if they fall under the percent specified by the filters.
	public boolean checkRange(ParallelAxis[] axisList, int curIndex, int startIndex, boolean started) {
		int add = 1;
		if(curIndex > axisList.length-1)
		{
			curIndex = 0;
			add = 0;
		}
		else if (curIndex == startIndex && started == false)
		{
			return false;
		}
		started = false;
		
		if(axisList[curIndex].isFilterEnabled())
		{
			C_VerticalDoubleSlider tmpSlider = (C_VerticalDoubleSlider)axisList[curIndex].getController();
			float xP = tmpSlider.getXPercent();
			float yP = tmpSlider.getYPercent();
			
			if (yPercent[curIndex] < (1-xP) && yPercent[curIndex] >= (1-yP)) {
				return (this.checkRange(axisList, curIndex+add, startIndex, started));
			}
			else {
				return true; // stop here and propagate back up to the beginning.
			}
		}
		else 
		{
			return (this.checkRange(axisList, curIndex+add, startIndex, started));
		}
	}
}
